package filter

import (
	"fmt"
	"strconv"
	"strings"
)

type RecordKind int
const (
	RecordBug = iota
	RecordOptimize
)

type Record struct {
	name string
	date string
	text string
	kind RecordKind
}

type LineKind int
const (
	LineTitle = iota
	LineBug
	LineOptimize
	LineOther
)

// boxerxiong(熊松) 1-28 20:45:18
func GetLineType(line string) LineKind {
	if strings.Count(line, "(") == 1 &&
		strings.Count(line, ")") == 1 &&
		strings.Count(line, "-") == 1 &&
		strings.Count(line, ":") == 2 {
		return LineTitle
	} else if strings.Contains(strings.ToLower(line), strings.ToLower("【bug】")) {
		return LineBug
	} else if strings.Contains(line, "【优化】") {
		return LineOptimize
	} else {
		return LineOther
	}
}

// boxerxiong(熊松) 1-28 20:45:18
func (r *Record)FillRecordTitle(line string) {
	var name string
	var nameSpec string
	var date string
	var time string

	if strings.Count(line, " ") == 3 {
		fmt.Sscanf(line, "%s %s %s %s", &name, &nameSpec, &date, &time)
	} else {
		fmt.Sscanf(line, "%s %s %s", &name, &date, &time)
	}

	fmt.Println(name, date, time)

	left := strings.Index(name, "(")
	r.name = name[0:left]

	heng := strings.Index(date, "-")
	month, _ := strconv.Atoi(date[:heng])
	day, _ := strconv.Atoi(date[heng+1:])
	r.date = fmt.Sprintf("2021-%02d-%02d", month, day)
}

func (r *Record)FillRecordBody(kind LineKind, line string) {
	if kind == LineBug {
		r.kind = RecordBug
	} else if kind == LineOptimize {
		r.kind = RecordOptimize
	}
	r.text = line
}

func AnalyseString(logstring string) []Record {
	records := make([]Record, 20)
	r := Record{}

	lines := strings.Split(logstring, "\n")
	for _, line := range lines {
		// 太短的行，直接返回
		if len(line) <= 3 {
			continue
		}

		// 获取行类型
		fmt.Println(line)
		kind := GetLineType(line)
		if kind == LineTitle {
			r.FillRecordTitle(line)
		} else if kind == LineBug || kind == LineOptimize {
			r.FillRecordBody(kind, line)
			records = append(records, r)
		}
	}

	return records
}

func Do(beginDate string, endDate string, isBug bool, isOptimize bool, logstring string) string {
	result := ""
	records := AnalyseString(logstring)
	for _, v := range records {
		// 日期过滤
		if v.date < beginDate || v.date > endDate {
			continue
		}
		// 类型过滤
		if !isBug && v.kind == RecordBug {
			continue
		}
		if !isOptimize && v.kind == RecordOptimize {
			continue
		}
		result += fmt.Sprintf("%s %s %s <br>", v.date, v.name, v.text)
	}
	return result
}
